package plugins.AI;

import com.alibaba.fastjson.JSONArray;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.gpt.IGPTAction;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.json.simple.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class GetCanteenDishesAction implements IGPTAction {

    @Override
    public Map<String, String> invokeAction(String action, Map<String, String> params) {
        Map<String, String> result = new HashMap<>();
        if ("GET_CANTEEN_DISHES".equalsIgnoreCase(action)) {
            String dishName = params.get("name");
            // String type = params.get("type");

            // 1. 定义查询字段（包含嵌套路径）
            String selectFields = "name, dcb4_merchant.name, dcb4_material, " +
                    "dcb4_nutritionfactslist.dcb4_project," +
                    "dcb4_nutritionfactslist.dcb4_contain," +
                    "dcb4_nutritionfactslist.dcb4_nvr," ;

            // 2. 执行查询
            QFilter filter = (new QFilter("name", QCP.equals, dishName));
            DynamicObject dishes = BusinessDataServiceHelper.loadSingle(
                    "dcb4_dishes", selectFields, new QFilter[]{filter}
            );

            // 3. 检查查询结果
            if (dishes == null) {
                result.put("error", "未找到菜品: " + dishName);
                return result;
            }

            // 4. 构建JSON响应
            JSONObject dishJson = new JSONObject();
            dishJson.put("name", dishes.getString("name"));
            dishJson.put("merchant", dishes.getString("dcb4_merchant.name"));
            dishJson.put("material", dishes.getString("dcb4_material"));

            JSONArray nutritionArray = new JSONArray();
            DynamicObjectCollection nutritionFactsList = dishes.getDynamicObjectCollection("dcb4_nutritionfactslist");

            for (DynamicObject nutritionFact : nutritionFactsList) {
                JSONObject nutritionJson = new JSONObject();
                nutritionJson.put("project", nutritionFact.getString("dcb4_project"));
                nutritionJson.put("contain", nutritionFact.getString("dcb4_contain"));
                nutritionJson.put("nvr", nutritionFact.getString("dcb4_nvr"));
                nutritionArray.add(nutritionJson);
            }

            dishJson.put("nutritionFacts", nutritionArray);

            // 5. 放入结果映射
            result.put("resultDynamicObject", dishJson.toJSONString());
            // result.put("type", type != null ? type : "default");


        }

        result.put("status", "success");

        return result;
    }

}
